package ch.rheintalconnection.sysventory.technicalServices;

import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.util.SubnetUtils;
import org.apache.commons.net.util.SubnetUtils.SubnetInfo;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import ch.rheintalconnection.sysventory.technicalServices.wmi.WMIHostScanner;
 
public class SingleThreadIpScanner implements IIpScanner {
	
	private static Logger logger = LogManager.getLogger(SingleThreadIpScanner.class);
			 

	public List<IHostScanner> scanIps(String ipmask) {
		
		SubnetUtils utils = new SubnetUtils(ipmask);
        SubnetInfo info = utils.getInfo();
        
        
        String[] ips = info.getAllAddresses();
        
    	// mit jeder IP ein Verbindungsaufbau testen
    	// falls ok in sauberes array, falls nicht -> Exception
        ArrayList<IHostScanner> hostscanners = new ArrayList<IHostScanner>();
        for(String address: ips){
        	try {
				Socket clientSocket = new Socket();
				
				SocketAddress addr = new InetSocketAddress(address, 135);
				clientSocket.connect(addr, 300);

				//ipsok.add(address);
				WMIHostScanner hostScanner = new WMIHostScanner(address);
				hostscanners.add(hostScanner);
				logger.info("Verbindung möglich: " + address);
				clientSocket.close();
			}
        	catch (com.jacob.com.ComFailException e) {
        		logger.info(e.getMessage() + " " + address);
        	}
        	catch (Exception e) {
				logger.info("Verbindung auf Socket nicht möglich: " + address);
			}        	
        }   
        return hostscanners;
	}
}